package com.service.db;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.service.other.Logger;

/**
 * 内部使用的用于保存连接池中连接对象的类 此类中有两个成员，一个是数据库的连接，另一个是指示此连接是否 正在使用的标志。
 */
public class PooledConnection {
	// 数据库连接
	private Connection connection = null;
	// 此连接是否正在使用的标志，默认没有正在使用
	private boolean busy; 
	// 构造函数，根据一个 Connection 构告一个 PooledConnection 对象
	public PooledConnection(Connection connection) {
		this.connection = connection;
	}

	public ResultSet executeQuery(String sql) throws SQLException {
		return connection.createStatement().executeQuery(sql);
	}

	public int executeUpdate(String sql) throws SQLException {
		return connection.createStatement().executeUpdate(sql);
	}

	// 返回此对象中的连接
	public Connection getConnection() {
		return connection;
	}
	
	public Statement prepareStatement(){
		Statement p = null;
		try {
			p = connection.createStatement();
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
		return p;
	}
	
	public PreparedStatement prepareStatement(String sql){
		PreparedStatement p = null;
		try {
			p = connection.prepareStatement(sql);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
		return p;
	}
	
	public PreparedStatement prepareStatement(String sql,int autoGeneratedKeys){
		PreparedStatement p = null;
		try {
			p = connection.prepareStatement(sql, autoGeneratedKeys);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
		return p;
	}
	
	public CallableStatement prepareCall(String sql){
		CallableStatement p = null;
		try {
			p = connection.prepareCall(sql);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
		return p;
	}
	
	public boolean getAutoCommit(){
		boolean autoCommit = false;
		try {
			autoCommit = connection.getAutoCommit();
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
		return autoCommit;
	}
	
	public void setAutoCommit(boolean value){
		try {
			connection.setAutoCommit(value);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
	}
	
	public void commit(){
		try {
			connection.commit();
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
	}
	
	// 设置此对象的，连接
	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	// 获得对象连接是否忙

	public boolean isBusy() {
		return busy;
	}

	// 设置对象的连接正在忙
	public void setBusy(boolean busy) {
		// System.out.println("set to busy:"+busy);
		this.busy = busy;
	}

	public void close() {
		busy = false;
	}
}